package com.ruoyi.web.controller.email;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.email.entity.EmailEntity;
import com.ruoyi.email.entity.FEmailEntity;
import com.ruoyi.email.service.EmailService;
import com.ruoyi.system.domain.SegRegEmailInfo;
import com.ruoyi.system.mapper.SegRegEmailInfoMapper;
import com.ruoyi.system.service.ISegRegEmailInfoService;
import com.ruoyi.system.service.ISegUploadDetailService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/system/email")
@Api(tags = "邮件服务")
public class EmailController {

    @Resource
    EmailService emailService;

    @Autowired
    ISysUserService iSysUserService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    public ISegRegEmailInfoService iSegRegEmailInfoService;

    @Autowired
    public ISegUploadDetailService iSegUploadDetailService;


    //    发送重置密码邮箱
    @RepeatSubmit()
    @PostMapping("/FEmail")
    public AjaxResult FEmail(@Validated @RequestBody FEmailEntity fEmailEntity) {
        SysUser temp = iSysUserService.selectUserByUserName(fEmailEntity.getUsername());
        if (temp != null){
            // 获取code
            String password = emailPassword();

            // 写入数据库
            SegRegEmailInfo segRegEmailInfo = new SegRegEmailInfo();
            segRegEmailInfo.setUserId(temp.getUserId());
            segRegEmailInfo.setCode(password); segRegEmailInfo.setType("1");
            iSegRegEmailInfoService.insertSegRegEmailInfo(segRegEmailInfo);

            // 发送邮件
            fEmailEntity.setSendTo(temp.getEmail());
            String FDetail = "您好！\n请通过下方验证码重置密码, 有效期5分钟。\n若非本人操作，可忽略此邮件。\n";
            fEmailEntity.setDetail(FDetail + password);
            fEmailEntity.setTitle("重置您的ARCUS密码");
            return emailService.sendSimpleMail(fEmailEntity);
        }
        return AjaxResult.error("用户不存在");

    }

    //    发送注册验证邮箱
//    @RepeatSubmit()
//    @PostMapping("/REmail")
//    public AjaxResult REmail(@Validated @RequestBody FEmailEntity fEmailEntity) {
//        SysUser user = iSysUserService.selectUserByUserName(fEmailEntity.getUsername());
//        if (user == null)
//            return AjaxResult.success("该账号不存在");
//        else if (user.getStatus().equals("0")) {
//            fEmailEntity.setSendTo(user.getEmail());
//            String code = redisCache.getCacheObject(fEmailEntity.getUsername()).toString();
//            String net = "http://localhost:8080/system/email/emailActivate/" + code;
//            String Hyperlink = String.format("<a href='%s'>【激活网址】</a>", net);
//            String FDetail = "您好！\n请通过下方链接激活账号。\n若非本人操作，可忽略此邮件。\n";
//            fEmailEntity.setDetail(FDetail + Hyperlink);
//            fEmailEntity.setTitle("激活您的ARCUS账号");
//            redisCache.setCacheObject(code, fEmailEntity.getUsername());
//            return emailService.sendSimpleMail(fEmailEntity);
//        }
//        return emailService.sendSimpleMail(fEmailEntity);
//    }

    // 忘记密码
    @PostMapping("/ForgetPassword")
    public AjaxResult forgetPassword(@RequestBody FEmailEntity fEmailEntity) {
        // 读取用户
        SysUser user = iSysUserService.selectUserByUserName(fEmailEntity.getUsername());
        if (user == null) {
            return AjaxResult.error("用户不存在");
        }

        // 查询验证码
        SegRegEmailInfo segRegEmailInfo = new SegRegEmailInfo();
        segRegEmailInfo.setUserId(user.getUserId()); segRegEmailInfo.setType("1");
        List<SegRegEmailInfo> emailInfoList = iSegRegEmailInfoService.selectSegRegEmailInfoList(segRegEmailInfo);
        Collections.reverse(emailInfoList);

        // 比较结果
        SegRegEmailInfo lastEmailInfo = emailInfoList.get(0);
        Calendar last = Calendar.getInstance();
        Calendar now = Calendar.getInstance();

        last.setTime(lastEmailInfo.getTime());
        last.add(Calendar.MINUTE, 5);
        now.setTime(new Date());

        if(now.after(last)){
            return AjaxResult.error("验证码已过期，请重新发送");
        }else if(!lastEmailInfo.getCode().equals(fEmailEntity.getEmailPassword())){
            return AjaxResult.error("验证码错误");
        }else{
            if (iSysUserService.resetUserPwd(fEmailEntity.getUsername(), SecurityUtils.encryptPassword(fEmailEntity.getPassword())) > 0)
                return AjaxResult.success("修改密码成功");
            return AjaxResult.error("修改密码失败");
        }
    }

    @GetMapping(value = "/emailActivate/{code}")
    public AjaxResult emailActivate(@PathVariable String code) {
        // @TODO 存在用户重复点击的bug

        String[] splitCode = code.split("_");
        if(splitCode.length != 2){
            return AjaxResult.error("网址格式错误");
        }

        SegRegEmailInfo temp = new SegRegEmailInfo();
        temp.setUserId(iSegUploadDetailService.userInfoConvert(splitCode[0], true).user_id);
        temp.setType("0");
        List<SegRegEmailInfo> emailInfoList = iSegRegEmailInfoService.selectSegRegEmailInfoList(temp);
        Collections.reverse(emailInfoList);

        if(emailInfoList.get(0).getCode().equals(splitCode[1])){
            SysUser user = iSysUserService.selectUserByUserName(splitCode[0]);
            user.setStatus("0");
            if (iSysUserService.updateUserStatus(user) > 0)
                return AjaxResult.success("激活成功，请进入登录页面登录您的账号");
        }
        return AjaxResult.error("验证码错误");
    }

    public String emailPassword() {
        StringBuilder flag = new StringBuilder();
        String sources = "0123456789";// 加上一些字母，就可以生成pc站的验证码了
        Random rand = new Random();
        for (int j = 0; j < 6; j++) {
            flag.append(sources.charAt(rand.nextInt(9)));
        }
        return flag.toString();
    }
}

